package newtest;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;


public class test2 {

    static String httpProtocol = "http";
    static String username = "hujie@abchinalife.com";//中银保信提供的对接账号
    static String password = "c65b5c4fc602c02c1daead8ee1219e74";//中银保信提供的对接账号的密码
    static String ip = "113.108.8.174";//中银保信双录服务器IP地址
    static int port = 3003;//中银保信双录服务器端口号
    static HttpHost target = null;
    static PoolingHttpClientConnectionManager cm = null;


    public static void main(String[] args) throws Exception {
        String businessNo = "6078bbf6-6a58-4197-8ca3-84326e1f3131";//业务识别号
        String filePath = "D:\\nongyin\\mspapp\\temp\\douleEntering\\PDF\\6078bbf6-6a58-4197-8ca3-84326e1f3131-insurance-F.pdf";//本地文件地址
        String fileCode = "19040";//保险公司管理员在双录系统后台配置的电子化文件的文件标识，该文件标识值会决定当前需要上传哪种类型的文件
        String fileMimeType = "application/pdf";//参考下方注释，比如要上传png文件，则传入image/png；如果上传pdf文件，则传入application/pdf
        /**
         * zkrsuncl@abchinalife.cn
         *
         * 保险条款 81000
         * 人身保险投保提示书 19040
         * 产品说明书 19041
         * 电子投保书 19043h19057
         * 免除保险人责任条款说明 19071
         *
         *
         * 待上传文件的fileMimeType值的说明：
         *      文件类型    mimeType值
         *      .jpg 	    image/jpg
         *      .png 	    image/png
         *      .pdf 	    application/pdf
         */
        for (int i = 0; i < 80; i++) {
            System.out.println("=============================次数:" + i);
            processRequest(businessNo, fileCode, filePath, fileMimeType);
        }
    }

    private static void processRequest(String businessNo, String fileCode, String filePath, String fileMimeType) throws IOException {
        HttpPost httpPost;
        CloseableHttpResponse response = null;
        try {
            HttpClientContext localContext = HttpClientContext.create();
            httpPost = new HttpPost(httpProtocol + "://" + ip + ":" + port + "/join/uploadElectronizationFiles");
            File file = new File(filePath);
            if (!file.exists()) {
                System.out.print("文件不存在!");
                return;
            }
            StringBody bodyBusinessNo = new StringBody(businessNo, ContentType.TEXT_PLAIN);
            StringBody bodyFileCode = new StringBody(fileCode, ContentType.TEXT_PLAIN);
            FileBody bin = new FileBody(file, ContentType.create(fileMimeType, Consts.UTF_8));

            HttpEntity entity = MultipartEntityBuilder
                    .create()
                    .setCharset(Charset.forName("utf-8"))
                    .addPart("file", bin)
                    .addPart("businessNo", bodyBusinessNo)
                    .addPart("fileCode", bodyFileCode)
                    .build();
            httpPost.setEntity(entity);
            response = createSSLClientDefault().execute(target, httpPost, localContext);

            System.out.println("------------------update userPortrait----------------------");
            StatusLine tLine = response.getStatusLine();
            System.out.println(tLine);
            int statusCode = tLine.getStatusCode();

            if (tLine.getStatusCode() == 200) {
                System.out.println("=========================正确啊");
            }
            HttpEntity responseEntity = response.getEntity();
            String data = IOUtils.toString(responseEntity.getContent(), "UTF-8");
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.close();
        }

    }

    /**
     * 获取受信任httpClient
     *
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault() {
        if (target == null) {
            target = new HttpHost(ip, port, httpProtocol);
        }

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, GetMD5.GetMD5Code(password)));

        System.out.println("=========================又来获取一次");
        try {
            return  HttpClients.custom()
                    .setDefaultCredentialsProvider(credsProvider)
                    .setConnectionManager(cm)
                    .build();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostConstruct
    public void init() {
        LayeredConnectionSocketFactory sslsf = null;
        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
                    null, new NoopHostnameVerifier());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf)
                .register("http", sslsf)
                .build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
    }
}


